import { createRouter, createWebHistory } from 'vue-router'
import {
  useUserStore,
} from "@/stores";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/example',
      redirect: '/' // 重定向到已存在的example路由
    },
    {
      path: '/',
      name: 'example',
      component: () => import('@/views/example.vue'),
    },
    {
      path: '/product',
      name: 'product',
      component: () => import('@/views/product.vue'),
    },
    {
      path: '/myCustom',
      name: 'myCustom',
      component: () => import('@/views/myCustom.vue'),
    },
    {
      path: '/my',
      name: 'my',
      component: () => import('@/views/my.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
  ],
})
// 添加路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 1. 定义无需登录的白名单路径
  const whiteList = ['/', '/login', '/404']
  
  // 2. 检查用户登录状态（根据实际存储方式调整）
  const hasToken = userStore.token || localStorage.getItem('ACCESS_TOKEN')
  console.log('hasToken',hasToken)
  console.log('hasToken2',localStorage.getItem('ACCESS_TOKEN'))
  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' }) // 已登录时禁止访问登录页
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 记录跳转来源
    }
  }
})
export default router
